package com.yawn.zerodefect.controller;

import com.yawn.zerodefect.controller.entity.RestResponse;
import com.yawn.zerodefect.util.EncryptUtil;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Created by yawn on 2018-01-26 11:49
 */
@Controller
public class AuthController {

    @Resource
    private IdentityService identityService;

    @PostMapping("/login")
    @ResponseBody
    public RestResponse login(@RequestBody com.yawn.zerodefect.entity.User loginUser, HttpSession session) {
        String userId = loginUser.getUserId();
        String encryptedPwd = EncryptUtil.md5Encrypt(loginUser.getPassword());
        boolean pwdCheck = identityService.checkPassword(userId, encryptedPwd);
        if (pwdCheck) {
            User user = identityService.createUserQuery().userId(userId).singleResult();
            List<Group> groupList = identityService.createGroupQuery().groupMember(userId).list();
            session.setAttribute("isLogin", true);
            session.setAttribute("user", user);
            session.setAttribute("groupList", groupList);
            return RestResponse.newInstance(1);
        }
        return RestResponse.newInstance(0, "用户名与密码不匹配！");
    }

    @GetMapping({"/logout", "/exit"})
    public String logout(HttpSession session) {
        session.removeAttribute("isLogin");
        session.removeAttribute("user");
        session.removeAttribute("groupList");
        return "redirect:/default";
    }

}
